package database

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type MongoDBConn struct {
	Client    *mongo.Client
	Ctx       context.Context
	CancelCtx context.CancelFunc
}

func NewMongoDBConn() *MongoDBConn {
	username := os.Getenv("DB_USERNAME")
	pwd := os.Getenv("DB_PWD")
	host := os.Getenv("DB_HOST")
	port := os.Getenv("DB_PORT")

	Client, err := mongo.NewClient(options.Client().ApplyURI(
		fmt.Sprintf("mongodb://%s:%s@%s:%s/", username, pwd, host, port)))
	if err != nil {
		log.Println(err)
		panic(err)
	}

	conn := MongoDBConn{
		Client: Client,
	}
	return &conn
}

func (conn *MongoDBConn) Connect() {
	Ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	err := conn.Client.Connect(Ctx)
	if err != nil {
		log.Println(err)
		panic(err)
	}
	conn.Ctx = Ctx
	conn.CancelCtx = cancel
}

func (conn *MongoDBConn) Close() {
	conn.Client.Disconnect(conn.Ctx)
	conn.CancelCtx()
}
